//
//  DDMyAnswerVC.m
//  dingdang
//
//  Created by 阮 沧晖 on 15/7/18.
//  Copyright (c) 2015年 阮 沧晖. All rights reserved.
//

#import "DDMyAnswerVC.h"
#import "DDMyAnswerContentVC.h"
#import "FSDropDownMenu.h"

#import "DDNetWorkAPIClient.h"
#import "ModelQuestionCourse.h"
@interface DDMyAnswerVC () <ViewPagerDataSource, ViewPagerDelegate,FSDropDownMenuDataSource,FSDropDownMenuDelegate>

@property(nonatomic,strong) NSArray *cityArr;
@property(nonatomic,strong) NSMutableArray *areaArr;
@property(nonatomic,strong) NSArray *currentAreaArr;
@property(nonatomic,assign) NSInteger curIndex;
@property(nonatomic,strong) FSDropDownMenu *menu;

@end

@implementation DDMyAnswerVC

- (void)viewDidLoad {
    
   
    
    // Keeps tab bar below navigation bar on iOS 7.0+
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    
    
    self.navigationController.navigationBarHidden = NO;
    self.title = @"我的回答";
    UIColor * color = [UIColor whiteColor];
    NSDictionary * dict=[NSDictionary dictionaryWithObject:color forKey:UITextAttributeTextColor];
    self.navigationController.navigationBar.titleTextAttributes = dict;
    //self.navigationController.navigationBar.hidden = NO;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"top_Background"] forBarMetrics:UIBarMetricsDefault];
    UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [back setFrame:CGRectMake(5,7, 22, 30)];
    [back setImage:[UIImage imageNamed:@"top_返回"] forState:UIControlStateNormal];
    [back addTarget:self action:@selector(popVC) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithCustomView:back];
    self.navigationItem.leftBarButtonItem = barButton;
    self.navigationController.navigationBar.hidden = NO;
    
    
    sleep(0.5);
    self.dataSource = self;
    self.delegate = self;
    
   
    [self createDropData];
    
    [super viewDidLoad];
    
    
    //[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(switchVC:) name:@"switchVC" object:nil];
    
    // self.tabWidth = self.view.frame.size.width/2;
}

-(void)createDropData
{
    _areaArr = [NSMutableArray array];
    DDNetWorkAPIClient *network = [[DDNetWorkAPIClient alloc]init];
    __weak DDMyAnswerVC *weakSelf = self;
    [network mainCoursetList:@{@"type":@"1"} completionBlock:^(BOOL isSuccess, NSString *message, NSString *status, id object) {
        NSMutableArray *array1 = [NSMutableArray array];
        [array1 addObject:@"全部"];
        ModelQuestionCourse *courses = (ModelQuestionCourse*)object;
        for (ModelQuestionCourseElement *element in courses.info_data) {
            [array1 addObject:element.info_title];
        }
        [_areaArr addObject:array1];
        
        if (courses) {
            [network mainDefaultCourseList:^(BOOL isSuccess, NSString *message, NSString *status, id object) {
                NSMutableArray *array2 = [NSMutableArray array];
                [array2 addObject:@"全部"];
                ModelQuestionCourse *courses = (ModelQuestionCourse*)object;
                for (ModelQuestionCourseElement *element in courses.info_data) {
                    [array2 addObject:element.info_title];
                }
                [_areaArr addObject:array2];
                
                if (courses) {
                    [network mainCoursetList:@{@"type":@"0"} completionBlock:^(BOOL isSuccess, NSString *message, NSString *status, id object) {
                        NSMutableArray *array3 = [NSMutableArray array];
                        [array3 addObject:@"全部"];
                        ModelQuestionCourse *courses = (ModelQuestionCourse*)object;
                        for (ModelQuestionCourseElement *element in courses.info_data) {
                            [array3 addObject:element.info_title];
                        }
                        [_areaArr addObject:array3];
                        
                        [weakSelf createDropMenu];
                        
                    }];
                }
            }];
        }
    }];

}


- (void)createDropMenu
{
    // Do any additional setup after loading the view, typically from a nib.
    UIButton *activityBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 62, 30)];
    activityBtn.titleLabel.font = [UIFont systemFontOfSize:14.f];
    [activityBtn setTitle:@"全部" forState:UIControlStateNormal];
    [activityBtn setImage:[UIImage imageNamed:@"expandableImage"] forState:UIControlStateNormal];
    activityBtn.imageEdgeInsets = UIEdgeInsetsMake(11, 52, 11, 0);
    [activityBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [activityBtn addTarget:self action:@selector(btnPressed:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:activityBtn];
    
    
    
    
    
    
    
    _cityArr = @[@"加密",@"悬赏",@"大家帮"];
//    _areaArr = @[
//                 @[@"全部",@"500米",@"1000米",@"2000米",@"5000米"],
//                 @[@"全部",@"徐家汇",@"人民广场",@"陆家嘴"],
//                 @[@"全部",@"三里屯",@"亚运村",@"朝阳公园"]
//                 ];
    
    _currentAreaArr = _areaArr[0];
    _menu = [[FSDropDownMenu alloc] initWithOrigin:CGPointMake(0, 44) andHeight:300];
    _menu.transformView = activityBtn.imageView;
    _menu.rightTableView.frame = CGRectMake(0, 0, 0, 0);
    _menu.leftTableView.frame = self.view.frame;//CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    _menu.tag = 1001;
    _menu.dataSource = self;
    _menu.delegate = self;
    [self.view addSubview:_menu];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}
-(void)popVC
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - ViewPagerDataSource
- (NSUInteger)numberOfTabsForViewPager:(ViewPagerController *)viewPager {
    return 3;
}
- (UIView *)viewPager:(ViewPagerController *)viewPager viewForTabAtIndex:(NSUInteger)index {
    
    UILabel *label = [UILabel new];
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont systemFontOfSize:20.0];
    
    switch (index) {
        case 0:
            label.text = @"加密题";
            break;
        case 1:
            label.text = @"悬赏题";
            break;
        case 2:
            label.text = @"大家帮";
            break;
        default:
            break;
    }
    
    
    
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = [UIColor colorWithRed:42.0/255.0 green:172.0/255.0 blue:226.0/255.0 alpha:0.75];
    [label sizeToFit];
    
    return label;
}

- (UIViewController *)viewPager:(ViewPagerController *)viewPager contentViewControllerForTabAtIndex:(NSUInteger)index {
    
    DDMyAnswerContentVC *cvc = [[DDMyAnswerContentVC alloc] initWithNibName:@"DDMyAnswerContentVC" bundle:nil];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:cvc];
    cvc.typeIndex = index;
    
    //cvc.labelString = [NSString stringWithFormat:@"Content View #%i", index];
    
    return nav;
}

#pragma mark - ViewPagerDelegate
- (CGFloat)viewPager:(ViewPagerController *)viewPager valueForOption:(ViewPagerOption)option withDefault:(CGFloat)value {
    
    switch (option) {
        case ViewPagerOptionStartFromSecondTab:
            return 0.0;
            break;
        case ViewPagerOptionCenterCurrentTab:
            return 0.0;
            break;
        case ViewPagerOptionTabLocation:
            return 1.0;
            break;
        case ViewPagerOptionTabWidth:
            return  [[UIApplication sharedApplication].delegate window].frame.size.width/3;
            break;
        case ViewPagerOptionTabOffset:
            return 0;
            break;
        default:
            break;
    }
    
    return value;
}
- (UIColor *)viewPager:(ViewPagerController *)viewPager colorForComponent:(ViewPagerComponent)component withDefault:(UIColor *)color {
    
    switch (component) {
        case ViewPagerIndicator:
            return [[UIColor colorWithRed:42.0/255.0 green:172.0/255.0 blue:226.0/255.0 alpha:0.75] colorWithAlphaComponent:0.64];
            break;
        default:
            break;
    }
    
    return color;
}

- (void)viewPager:(ViewPagerController *)viewPager didChangeTabToIndex:(NSUInteger)index
{
    _curIndex = index;
    NSLog(@"%lu",(unsigned long)index);
    
    //if(tableView == menu.rightTableView){
    if (_areaArr && _areaArr.count > index) {
        
        [self resetItemSizeBy:@"全部"];
        //0:加密 1:悬赏 2:大家帮
        NSString *typeText = [NSString stringWithFormat:@"%ld_%@",(long)_curIndex,@"全部"];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"didChangeText" object:typeText];
        _currentAreaArr = _areaArr[index];
        [_menu.leftTableView reloadData];
    }
    
    //}else{
    //    [self resetItemSizeBy:_currentAreaArr[indexPath.row]];
    //}
}

-(void)switchVC:(NSNotification *)note
{
    UIViewController *vc = note.object;
    [self presentViewController:vc animated:YES completion:nil];
    //[self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 下拉菜单
-(void)btnPressed:(id)sender{
    if (_areaArr && _areaArr.count > _curIndex) {
        _currentAreaArr = _areaArr[_curIndex];
        [_menu.leftTableView reloadData];
    }
    
    
    FSDropDownMenu *menu = (FSDropDownMenu*)[self.view viewWithTag:1001];
    [UIView animateWithDuration:0.2 animations:^{
        
    } completion:^(BOOL finished) {
        [menu menuTapped];
    }];
}

#pragma mark - reset button size

-(void)resetItemSizeBy:(NSString*)str{
    UIButton *btn = (UIButton*)self.navigationItem.rightBarButtonItem.customView;
    [btn setTitle:str forState:UIControlStateNormal];
    NSDictionary *dict = @{NSFontAttributeName:btn.titleLabel.font};
    CGSize size = [str boundingRectWithSize:CGSizeMake(150, 30) options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil].size;
    btn.frame = CGRectMake(btn.frame.origin.x, btn.frame.origin.y,size.width+33, 30);
    btn.imageEdgeInsets = UIEdgeInsetsMake(11, size.width+23, 11, 0);
}


#pragma mark - FSDropDown datasource & delegate

- (NSInteger)menu:(FSDropDownMenu *)menu tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView == menu.rightTableView) {
        return _cityArr.count;
    }else{
        return _currentAreaArr.count;
    }
}
- (NSString *)menu:(FSDropDownMenu *)menu tableView:(UITableView*)tableView titleForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == menu.rightTableView) {
        
        return _cityArr[indexPath.row];
    }else{
        return _currentAreaArr[indexPath.row];
    }
}


- (void)menu:(FSDropDownMenu *)menu tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if(tableView == menu.rightTableView){
        _currentAreaArr = _areaArr[_curIndex];
        [menu.leftTableView reloadData];
    }else{
        [self resetItemSizeBy:_currentAreaArr[indexPath.row]];
        if (_currentAreaArr[indexPath.row]) {
            
            NSString *text = _currentAreaArr[indexPath.row];
            //0:加密 1:悬赏 2:大家帮
            NSString *typeText = [NSString stringWithFormat:@"%ld_%@",(long)_curIndex,text];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"didChangeText" object:typeText];
        }
    }
    
}
@end
